"use strict";
const { Op } = require("sequelize");
const Service = require("egg").Service;
const tree = require("../../utils/tree");
class DemoService extends Service {
  // 查询信息列表
  async list(params) {
    const { app } = this;
    try {
      const limit = Number(params.pageSize) || 10; // 当页条数
      const offset = Number(params.pageSize) * (Number(params.page) - 1) || 0; // 开始下标
      const data = await app.model.Menu.findAll({
        limit,
        offset,
        where: {
          [Op.or]: [{ type: 0 }, { type: 1 }]
        }
      });
      const total = await app.model.Menu.count();
      return {
        code: 200,
        data: tree(
          JSON.parse(JSON.stringify(data)),
          "id",
          "parentId",
          "children"
        ),
        page: offset + 1,
        pageSize: limit,
        total,
        message: "获取列表成功"
      };
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }
  // node节点全部
  async node(params) {
    const { app } = this;
    try {
      const data = await app.model.Menu.findAll({
        attributes:['id','name','parentId'],
        where: {
          [Op.or]: [{ type: 0 }, { type: 1 }]
        }
      });
      const total = await app.model.Menu.count();
      return {
        code: 200,
        data: tree(
          JSON.parse(JSON.stringify(data)),
          "id",
          "parentId",
          "children"
        ),
        total,
        message: "获取菜单成功"
      };
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }

  // 查询信息详细
  async detail(params) {
    const { app } = this;
    try {
      const data = await app.model.Menu.findOne({
        where: params
      });
      return {
        code: 200,
        data,
        message: "获取详细成功"
      };
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }

  // 新增信息
  async add(params) {
    const { app } = this;
    try {
      let UUID = uuidv1();
      params.lesseeId = "ZH" + "-" + UUID;
      const data = await app.model.Menu.create(params);

      if (data) {
        return {
          code: 200,
          message: "新增成功"
        };
      }
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }

  // 修改信息
  async update(params) {
    const { app } = this;
    try {
      await app.model.Menu.update(params, {
        where: {
          lesseeID: params.lesseeID
        }
      });
      return {
        code: 200,
        message: "修改成功"
      };
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }
  // 删除信息
  async delete(params) {
    const { app } = this;
    try {
      await app.model.Menu.destroy({
        where: params
      });
      return {
        code: 200,
        message: "删除成功"
      };
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }
}

module.exports = DemoService;
